/*
 * 文 件 名 : HomeActivity.java
 * 版    权 : China Machi.Co.,Ltd.Copyright 2009-2011.All rights reserved
 * 描    述 : <描述>
 * 修 改 人 : lixg
 * 修改时间 : 2012-8-4
 * 跟踪单号 : <跟踪单号>
 * 修改单号 : <修改单号>
 * 修改内容 : <修改内容>
 */
package com.fire8.dolphin.ui.chat;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fire8.dolphin.db.ChatDAO;
import com.fire8.dolphin.db.FriendDAO;
import com.fire8.dolphin.model.ChatRecord;
import com.fire8.dolphin.model.Friend;
import com.fire8.dolphin.service.JaberClientService;
import com.fire8.dolphin.ui.DolphinApplication;
import com.fire8.dolphin.ui.PopupFaceViewWindow;
import com.fire8.dolphin.ui.R;
import com.fire8.dolphin.ui.UserInfoActivity;
import com.fire8.dolphin.ui.imgcache.AsynLoad;
import com.fire8.dolphin.utils.DateUtil;
import com.fire8.dolphin.utils.LogUtil;
import com.fire8.dolphin.utils.SmileyParser;
import com.fire8.dolphin.utils.StringUtil;
import com.fire8.dolphin.web.RequestUtils;

/**
 * 主页面
 * 显示全部问题
 *
 * @author  lixg
 * @version [版本号,2012-8-4]
 * @see     [相关类/方法]
 * @since   [产品/模块]
 */
public class ChatActivity extends Activity implements OnItemClickListener
{
    private DolphinApplication app;
    private RelativeLayout layout;
    private ListView listView;
    private List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    private MyAdapter myAdapter;
    private ChatDAO dao;
    private FriendDAO friendDao;
    private JaberClientService jaberClientService;
    private AsynLoad asynLoad;
    
    private String userId;
    private static String account="";
    private String userName;
    //private String userHead;
    private SmileyParser smileyParser;
    
    private Bitmap selfHead;//自己的头像
    private Bitmap friendHead;//对方的头像
    
    private PopupWindow popButtonWin;
    private TextView tvTitle;
    private Button btnText;
    //private ImageButton btnVoice;
    private ImageButton btnFace;
    private EditText txtAnswer;
    private Button btnRight;
    private Button btnLeft;
    //private LinearLayout layoutInputContext;
    
    private static boolean openFlag=false;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat);
        app = (DolphinApplication)getApplication();
        dao = new ChatDAO(this);
        friendDao = new FriendDAO(this);
        smileyParser = SmileyParser.getInstance(this);
        jaberClientService = JaberClientService.getInstance();
        IntentFilter filter = new IntentFilter("com.fire8.dolphin.ui.ChatActivity");
        this.registerReceiver(mReceiver, filter);
        //异步加载头像
        asynLoad = new AsynLoad();
        
        layout  = (RelativeLayout)findViewById(R.id.layout_chat);
        //jaberClientService.addMessageListener(processHandler);
        listView = (ListView)findViewById(R.id.chat_list);
        //listView.setOnItemClickListener(this);
        userId = getIntent().getStringExtra("userId");
        userName = getIntent().getStringExtra(Friend.C_USER_NAME);
        //userHead = getIntent().getStringExtra(Friend.C_USER_HEAD);
        account = getIntent().getStringExtra(Friend.C_ACCOUNT);
        btnLeft = (Button)findViewById(R.id.title_bt_left);
        btnRight = (Button)findViewById(R.id.title_bt_right);
        tvTitle = (TextView)findViewById(R.id.tv_bar_title);
        tvTitle.setText(userName==null?account:userName);
        btnText = (Button)findViewById(R.id.btn_enter);
        btnFace = (ImageButton)findViewById(R.id.btn_input_face);
        txtAnswer = (EditText)findViewById(R.id.txt_answer);
        //btnVoice = (ImageButton)findViewById(R.id.btn_input_voice);//语音输入
        
        //layoutInputContext = (LinearLayout)findViewById(R.id.layout_input_context);
//        btnVoice.setOnClickListener(new InputBarListener(this,
//                layoutInputContext, mHandler));
//        btnFace.setOnClickListener(new InputBarListener(this,
//                layoutInputContext, mHandler));
//        btnText.setOnClickListener(new InputBarListener(this,
//                layoutInputContext, mHandler));
        setElement();
        myAdapter = new MyAdapter(this);
        listView.setAdapter(myAdapter);
        findChatRecodes();
        
    }
    
    private void setElement()
    {
        btnRight.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                createPopupWindow(v);
            }
        });
//        btnVoice.setOnClickListener(new InputBarListener(this,
//                layoutInputContext, mHandler));
        btnFace.setOnClickListener(new OnClickListener()
        {
            
            @Override
            public void onClick(View v)
            {
                
                //关闭软件键盘
                InputMethodManager imm = (InputMethodManager)ChatActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE); 
                imm.hideSoftInputFromWindow(txtAnswer.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                //弹出表情输入窗口
                PopupFaceViewWindow editWindow = PopupFaceViewWindow.getInstall(ChatActivity.this,mHandler);
                if (editWindow.isShowing())  
                {
                    LogUtil.d("隐藏窗口");
                    editWindow.dismiss(); 
                }
                else {  
                    LogUtil.d("显示窗口");
                    editWindow.showAsDropDown(v,0, 0);
                    //editWindow.showAtLocation(layoutInputContext.findViewById(R.id.layout_answer), Gravity.RIGHT|Gravity.BOTTOM, 0,46);
                }
            }
        });
        btnText.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                
                String strAnswer = txtAnswer.getText().toString();
                if(StringUtil.isEmpty(strAnswer))
                {
                    //Toast.makeText(ChatActivity.this, "请输入回答内容", Toast.LENGTH_LONG).show();
                    return;
                }
                txtAnswer.setText("");
                saveChatItem(ChatRecord.ITEM_TYPE_TEXT, strAnswer,ChatRecord.ITEM_IO_OUT);
                new SendMsgTask().execute(strAnswer);
            }
        });
        btnLeft.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //返回按钮，将聊天窗口关闭
                ChatActivity.this.finish();
            }
        });
    }
    
    @Override
    protected void onPause()
    {
        openFlag=false;
        super.onPause();
    }


    @Override
    protected void onStart()
    {
        openFlag=true;
        super.onStart();
        //启动时把好友表hasMsg标志设为无消息
        friendDao.hasMsg(account, Integer.valueOf("0"));
        //删除通知栏
        NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        mNotificationManager.cancel(account.hashCode());
    }
    public static boolean isOpen()
    {
        return openFlag;
    }
    public static String getCurrertAccount()
    {
        return account;
    }
    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }


    private void findChatRecodes()
    {
        ChatRecord cr = new ChatRecord();
        if(!StringUtil.isEmpty(userId))
        {
            //cr.setUserId(Integer.valueOf(userId));
        }
        cr.setAccount(account);
        list = dao.findList(cr);
        LogUtil.d("record len "+list.size());
        myAdapter.notifyDataSetChanged();
        LogUtil.d("findchat record");
        //投递一个消息进行滚动  
        //mHandler.post(mScrollToBottom);  
    }
    
    
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id)
    {
        
    }
    
    
    
    public class MyAdapter extends BaseAdapter
    {
        private LayoutInflater mInflater;
        
        public MyAdapter(Context context)
        {
            this.mInflater = LayoutInflater.from(context);
        }
        
        public int getCount()
        {
            return list.size();
        }
        
        public Object getItem(int position)
        {
            return null;
        }
        
        public long getItemId(int position)
        {
            return 0;
        }
        
        public View getView(int position, View convertView, ViewGroup parent)
        {
            HashMap<String, String> map = list.get(position);
            String io = map.get(ChatRecord.C_ITEM_IO);
            ViewHolder holder = null;
            holder = new ViewHolder();
            if(ChatRecord.ITEM_IO_IN.equals(io))
            {
                convertView = mInflater.inflate(R.layout.chat_item_left, null);
            }else
            {
                convertView = mInflater.inflate(R.layout.chat_item_right, null);
                
            }
            
            holder.imgHead = (ImageView)convertView.findViewById(R.id.img_head);
            holder.tvChat = (TextView)convertView.findViewById(R.id.tv_item);
            //holder.tvPoint = (TextView)convertView.findViewById(R.id.tv_point);
            holder.tvDate = (TextView)convertView.findViewById(R.id.tv_date);
            convertView.setTag(holder);
//            
//            if (convertView == null)
//            {
//                
//            }
//            else
//            {
//                holder = (ViewHolder)convertView.getTag();
//            }
            String itemType = map.get(ChatRecord.C_ITEM_TYPE);
            if(ChatRecord.ITEM_TYPE_TEXT.equals(itemType))
            {
                Spannable spans = smileyParser.addSmileySpans(map.get(ChatRecord.C_CHAT_ITEM));//将文字转换为图形
                holder.tvChat.setText(spans);
                holder.tvChat.setVisibility(View.VISIBLE);
            }
            //String userName = map.get(Friend.C_USER_NAME);
            //holder.tvUserName.setText(userName);
            
            holder.tvDate.setText(map.get(ChatRecord.C_CHAT_DATE));
            if(ChatRecord.ITEM_IO_IN.equals(io))
            {
                //对方
                if(friendHead == null)
                {
                    friendHead = asynLoad.showimgAnsy(holder.imgHead,RequestUtils.IMG_URL+userId+".jpg");
                }else
                {
                    holder.imgHead.setImageBitmap(friendHead);
                }
                
            }else
            {
                //自己
                
                if(selfHead == null)
                {
                    asynLoad.showimgAnsy(holder.imgHead,RequestUtils.IMG_URL+app.getUserId()+".jpg");
                }else
                {
                    holder.imgHead.setImageBitmap(selfHead);
                }
            }
            
            return convertView;
        }
        class ViewHolder
        {
            public ImageView imgHead;
            public TextView tvChat;
            public TextView tvDate;
        }
    }
    //处理输入栏反回的数据
    private final Handler mHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            //Log.i(TAG, "face: " + msg.arg1);
            //String strAnswer = "";
            switch (msg.what)
            {
                case R.id.btn_input_voice:
                    //strAnswer = (String)msg.obj;
                    //saveAnswer(Answer.CONTEXT_TYPE_VOICE, strAnswer);
                    break;
                case R.id.btn_input_face:
                    String text = (String)msg.obj;
                    Spannable spans = smileyParser.addSmileySpans(text);//将文字转换为图形
                    //EditText txtAnswer = (EditText)layoutInputContext.findViewById(R.id.txt_answer);
                    txtAnswer.getEditableText().append(spans);//将图形追加到文本框
                    break;
                case R.id.btn_input_doodle:
                    
                    break;
                case R.id.btn_input_pic:
                    
                    break;
                case R.id.btn_input_text:
                    //strAnswer = (String)msg.obj;
                    saveChatItem(ChatRecord.ITEM_TYPE_TEXT, (String)msg.obj,ChatRecord.ITEM_IO_OUT);
                    new SendMsgTask().execute((String)msg.obj);
                    break;
                default:
                    break;
            }
            
        }
    };
    
    private void saveChatItem(String type,String msg,String io)
    {
        ChatRecord cr = new ChatRecord();
        if(!StringUtil.isEmpty(userId))
        {
            cr.setUserId(Integer.valueOf(userId));
        }
        cr.setAccount(account);
        
        cr.setItemIO(io);
        cr.setItemType(type);
        cr.setChatItem(msg);
        cr.setChatDate(DateUtil.dateToStr(new Date(),
                "yyyy-MM-dd HH:mm:ss"));
        dao.add(cr);
        findChatRecodes();
    }
    
    class SendMsgTask extends AsyncTask<String, Void, String> 
    {

        @Override
        protected String doInBackground(String... params)
        {
            try {
                jaberClientService.sendMessage(account, params[0]);
            } catch (Exception e) {
                LogUtil.e("发送消息异常了", e);
            }
            return null;
        }
        
    }
    private final BroadcastReceiver mReceiver = new BroadcastReceiver(){

        @Override
        public void onReceive(Context arg0, Intent arg1)
        {
            //刷新页面
            findChatRecodes();
        }
        
    };
        
    /**
     * 右上角按钮弹出菜单窗口
     * 1、查看好友信息
     * 2、删除聊天记录
     * @param v [参数说明]
     *
     * @author lixg
     * @see [类、类#方法、类#成员]
     */
    private void createPopupWindow(View v){   
        if(popButtonWin == null)
        {
            LayoutInflater factory = LayoutInflater.from(this);  //加载popWindow的layout   
            final View buttonView = factory.inflate(R.layout.chat_popup_button, null);   
            //Button btnAbout = (Button)buttonView.findViewById(R.id.btnAbout);
            popButtonWin = new PopupWindow(buttonView,200,270); //请注意，使用此构造方法，一定要指定popupWindow的长宽，之后调用popupWindow的showAXXX方法才会显示指定的contentView
            ColorDrawable cd = new ColorDrawable(-0000);
            popButtonWin.setBackgroundDrawable(cd);
            popButtonWin.setFocusable(true);
            popButtonWin.setTouchInterceptor(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if(event.getAction() == MotionEvent.ACTION_OUTSIDE)
                    {
                        Log.d("haoyuntu","按到外面了，关闭窗口");
                        popButtonWin.dismiss();
                        return true;
                    }
                    return false;
                }
            });
            popButtonWin.getContentView().findViewById(R.id.btn_userinfo).setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ChatActivity.this,
                            UserInfoActivity.class);
                    //intent.putExtra("from", "answer");
                    intent.putExtra("userId", userId);
                    startActivity(intent);
                    popButtonWin.dismiss();
                }
            });
            popButtonWin.getContentView().findViewById(R.id.btn_del_chat).setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View v) {
                    
                    popButtonWin.dismiss();
                    AlertDialog.Builder dialog = new AlertDialog.Builder(
                            ChatActivity.this);
                    dialog.setTitle("删除聊天记录");
                    dialog.setMessage("确认要删除聊天记录吗");
                    dialog.setPositiveButton("确定",
                            new DialogInterface.OnClickListener()
                            {
                                @Override
                                public void onClick(DialogInterface dialog, int which)
                                {
                                    dao.delete(account);
                                }
                            });
                    dialog.setNegativeButton("取消",null);
                    dialog.create().show();
                }
            });
            
        }
        if(popButtonWin.isShowing())
        {
            popButtonWin.dismiss();
        }else
        {
            popButtonWin.showAsDropDown(v,10, 0);
        }
    } 
}
